<template>
  <van-tabbar class="tabs" :border="false" v-model="active" @change="onChange">
    <van-tabbar-item v-for="(item, index) of navs" :key="index">
      <template #icon="props">
        <img :src="props.active ? item.iconActive : item.icon" />
      </template>
      <span>{{ $t(item.name) }}</span>
    </van-tabbar-item>
  </van-tabbar>
</template>

<script>
import { Tabbar, TabbarItem } from "vant";
import { ref, watch } from "vue";
import { useRoute, useRouter } from "vue-router";

export default {
  components: {
    [Tabbar.name]: Tabbar,
    [TabbarItem.name]: TabbarItem,
  },
  setup(params, ctx) {
    const swiper = ref(null);
    const active = ref(0);
    const route = useRoute();
    const router = useRouter();
    const navs = [
      {
        name: "首页",
        icon: require(`../assets/img/tab1.png`),
        iconActive: require(`../assets/img/tab1_active.png`),
      },
      {
        name: "交易",
        icon: require(`../assets/img/tab2.png`),
        iconActive: require(`../assets/img/tab2_active.png`),
      },
      {
        name: "账户",
        icon: require(`../assets/img/tab3.png`),
        iconActive: require(`../assets/img/tab3_active.png`),
      },
      {
        name: "我的",
        icon: require(`../assets/img/tab4.png`),
        iconActive: require(`../assets/img/tab4_active.png`),
      },
    ];
    watch(
      () => route.name,
      (_new) => {
        if (_new == "home") {
          const _active = route.params.active << 0
          active.value =  _active < navs.length && _active || 0
        }
      },
      {
        immediate: true,
      }
    );

    function onChange(active) {
      if (route.name == "home") {
        router.replace({ params: { active: active } });
        swiper.value.swipeTo(active, { immediate: true });
      } else {
        router.replace({ name: "home", params: { active: active } });
      }
    }

    return {
      swiper,
      active,
      navs,
      onChange,
    };
  },
};
</script>